import Axios from "axios";
import { message } from "antd";

Axios.defaults.headers.post["Content-Type"] = "application/json";

let jsonRequest = {
  timeout: 15000,
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest"
  },
  data: {}
};

let header_form = {
  Accept: "application/json",
  "Content-Type": "application/x-www-form-urlencoded",
  "X-Requested-With": "XMLHttpRequest"
};

let header_formdata = {
  "Transfer-Encoding": "Chunked",
  "Content-Type": "multipart/form-data",
  "X-Requested-With": "XMLHttpRequest"
};

/**
 * 检测 Token 并默认设置
 * @param {*} method POST(default),GET
 * @param {*} type undefined(default) = json header, 1:form header, 2:formdata header
 */
const initRequest = (method = "POST", type) => {
  let headers = {};
  switch (type) {
    case 1:
      headers = { ...header_form };
      break;
    case 2:
      headers = { ...header_formdata };
      break;
    default:
      //json
      break;
  }
  let headRequest = { ...jsonRequest, method, headers };
  headRequest.headers.token = sessionStorage.getItem("token");
  return headRequest;
};

const get = (url, params = {}) => {
  url = getParamsUrl(url, params);
  return requestNetwork(url, initRequest("GET"));
};

const post = (url, params = {}) => {
  let request = initRequest();

  if (params) {
    request.data = JSON.stringify(params);
  }
  return requestNetwork(url, request);
};

const postForm = (url, params = {}) => {
  let request = initRequest("GET");
  let formdata = "";
  if (params) {
    for (let key in params) {
      let value = params[key];
      formdata += key + "=" + String(value) + "&";
    }
    formdata = formdata.substr(0, formdata.length - 1);
  }
  request.body = formdata;
  return requestNetwork(url, request);
};

//Form Submit Third Library Invoke
const postFileForm = (url, params) => {
  let request = initRequest("GET");
  let formdata = new FormData();
  if (params) {
    for (let key in params) {
      let item = params[key];
      if (item && item.isFile) {
        formdata.push({ name: key, filename: key }); //item.data = uri path(file://)
      } else formdata.push({ name: key, data: String(item) });
    }
  }
  request.body = formdata;
  return requestNetwork(url, request);
};

function requestNetwork(url, request, isSave) {
  //post=true use header
  try {
    return requestAction(url, request, isSave);
  } catch (e) {
    return exception(e);
  } finally {
    //TODO
  }
}

function requestAction(url, request, isSave) {
  return (
    Axios(url, request)
      // .then((response) => response.json()) //可预先处理状态或其他行为
      .then(
        responseJson => {
          //请求正常
          let data = responseJson.data;
          console.log("dev_result: => " + JSON.stringify(responseJson));
          let ret = processResult(data);
          return { data, ret };
        },
        error => {
          //请求失败
          console.log("dev_error: => " + JSON.stringify(error));
          return exception(error);
        }
      )
      .catch(e => {
        console.log("dev_catch: => " + JSON.stringify(e));
        return exception(e);
      })
  );
}

//结果预处理
function processResult(retJson) {
  try {
    if (retJson) {
      //ret == undefined => false
      if (retJson.code === 200) {
        delete retJson.code;
        delete retJson.msg;
        return { code: true };
      } else if (retJson.code === 4001) {
        message.error("无效用户,请重新登录 - " + retJson.code);
        return retJson;
      } else {
        message.error(retJson.msg + "-" + retJson.code);
        return retJson;
      }
    } else message.error(retJson.msg + "-" + retJson.code);
  } catch (e) {
    return exception({ msg: e.message, code: "程序异常" });
  }
}

function exception(ret) {
  //程序异常
  let { code, msg } = ret;
  // Toast.hide();
  // setTimeout(() => Toast.offline(title + ': ' + msg, 2), 50);
  console.error(code, msg);
  message.error(code + "[" + msg + "]");
  return {
    ret: {
      code,
      msg
    }
  };
}

//url中@占位符替换
function getParamsUrl(url, params) {
  if (!params) return url;
  let paramsUri = "?";
  for (let key in params) {
    let value = params[key];
    paramsUri += key + "=" + value + "&";
  }
  return (url += paramsUri.substr(0, paramsUri.length - 1));
}

export { get, post, postForm, postFileForm };
